package org.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.app.common.Result;
import org.app.dto.UserLoginDTO;
import org.app.dto.UserRegisterDTO;
import org.app.entity.User;
import org.app.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        Map<String, Object> data = userService.login(loginDTO);
        return Result.success(data);
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        userService.register(registerDTO);
        return Result.success();
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        User user = userService.getById(userId);
        if (user != null) {
            user.setPassword(null); // 不返回密码
        }
        return Result.success(user);
    }
    
    /**
     * 分页查询用户列表（管理员接口）
     */
    @GetMapping("/page")
    public Result<Page<User>> getUserPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        Page<User> page = userService.getUserPage(pageNum, pageSize, keyword);

        log.info(page.toString());
        // 移除密码
        for (User user : page.getRecords()) {
            user.setPassword(null);
        }
        
        return Result.success(page);
    }
    
    /**
     * 更新用户状态（管理员接口）
     */
    @PutMapping("/status/{userId}")
    public Result<Void> updateUserStatus(
            @PathVariable Long userId,
            @RequestParam Integer status) {
        userService.updateUserStatus(userId, status);
        return Result.success();
    }
    
    /**
     * 获取用户详情（管理员接口）
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user != null) {
            user.setPassword(null); // 不返回密码
        }
        return Result.success(user);
    }
    
    /**
     * 添加用户（管理员接口）
     */
    @PostMapping
    public Result<Void> addUser(@Valid @RequestBody User user) {
        // 检查用户名是否已存在
        User existUser = userService.getByUsername(user.getUsername());
        if (existUser != null) {
            return Result.error("用户名已存在，请使用其他用户名");
        }
        userService.save(user);
        return Result.success();
    }
    
    /**
     * 更新用户（管理员接口）
     */
    @PutMapping
    public Result<Void> updateUser(@Valid @RequestBody User user) {
        // 如果密码为空，不更新密码字段
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            User existingUser = userService.getById(user.getId());
            if (existingUser == null) {
                return Result.error("用户不存在");
            }
            user.setPassword(existingUser.getPassword());
        }
        userService.updateById(user);
        return Result.success();
    }
    
    /**
     * 删除用户（管理员接口）
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success();
    }
    
    /**
     * 重置用户密码（管理员接口）
     */
    @PostMapping("/{id}/password/reset")
    public Result<String> resetPassword(@PathVariable Long id) {
        String newPassword = userService.resetPassword(id);
        return Result.success(newPassword);
    }
    
    /**
     * 更新当前用户信息（用户端接口）
     */
    @PutMapping("/update")
    public Result<Void> updateCurrentUser(@RequestBody Map<String, Object> userInfo, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 只允许修改昵称和手机号
        if (userInfo.containsKey("nickname")) {
            user.setNickname((String) userInfo.get("nickname"));
        }
        if (userInfo.containsKey("phone")) {
            user.setPhone((String) userInfo.get("phone"));
        }
        
        userService.updateById(user);
        return Result.success();
    }
    
    /**
     * 修改当前用户密码（用户端接口）
     */
    @PutMapping("/password")
    public Result<Void> changePassword(@RequestBody Map<String, String> passwordInfo, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        String oldPassword = passwordInfo.get("oldPassword");
        String newPassword = passwordInfo.get("newPassword");
        log.info(passwordInfo.toString());
        if (oldPassword == null || newPassword == null) {
            return Result.error("密码不能为空");
        }
        
        // 验证新密码长度
        if (newPassword.length() < 6 || newPassword.length() > 16) {
            return Result.error("新密码长度应为6-16位");
        }
        
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        if (!success) {
            return Result.error("原密码不正确");
        }
        
        // 返回特殊状态码，前端检测到此状态码后自动退出登录
        return Result.success(null, "密码修改成功，请重新登录", 201);
    }
    
    /**
     * 上传用户头像（用户端接口）
     */
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        
        if (file.isEmpty()) {
            return Result.error("请选择文件");
        }
        
        log.info(file.toString());
        try {
            String avatarUrl = userService.uploadAvatar(userId, file);
            log.info(avatarUrl);
            return Result.success(avatarUrl);
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return Result.error("上传头像失败: " + e.getMessage());
        }
    }
} 